"use strict";
// 解析树
export function listToTree({list, fields, openIds}) {
    /*把所有节点以parentId分组*/
    function getNodeGroup (nodeList) {
        var group = {};
        for (let i = 0; i < nodeList.length; i++) {
            nodeList[i].open = false;
            group["" + nodeList[i][fields.pid]] = [];
        }
        for (let j = 0; j < nodeList.length; j++) {
            group["" + nodeList[j][fields.pid]].push(nodeList[j]);
        }
        return group;
    }
    /*筛选出一级节点  把所有无父节点的节点都看成是顶级节点*/
    function findAllroot (group, nodesMap, fields) {
        var rootNodes = []
        for (let key in group) {
            if(Object.keys(nodesMap).indexOf(key) == -1){
                rootNodes = rootNodes.concat(group[key])
            }
        }
        return rootNodes
    }
    /*修改添加节点属性*/
    function nodeRender (dataList, nodeGroup, path=[]) {
        var item;
        for (let index = 0; index < dataList.length; index++) {
            item = dataList[index];
            if (path.length == 0) {
                item.isLeaf = false;
                path_record["" + item[fields.id]] = [index];
                item.level = path.length + 1;
                item.nodePath = [index];
            } else {
                item.isLeaf = !hasChild(item, nodeGroup);
                item.level = path.length + 1;
                path_record["" + item[fields.id]] = path.concat(index);
                item.nodePath = path.concat(index);
            }
        }
    }
    /*设置展开至顶级节点*/
    function openToRoot(nodeTree, ids) {
        ids.forEach((id, index) => {
            var tem = nodeTree;
            var path = path_record["" + id];
            if (path) {
                path.forEach((item, index) => {
                    if (index == 0) {
                        tem = tem[item];
                    } else {
                        tem = tem.children[item];
                    }
                    tem.open = true
                })
            }
        })
    }
    function hasChild(node, nodeGroup) {
        if (nodeGroup) {
            return nodeGroup.hasOwnProperty("" + node[fields.id]);
        } else {
            return false;
        }
    }
    function getNodesMap(list){
        let map = {}
        list.forEach((item)=>{
            map[item.id] = item
        })
        return map
    }
    function main(data) {
        if (!data || data.length == 0) {
            return {tree: [], path: {}};
        }
        let rootList = [],
        tree = [],
        nodeGroup = getNodeGroup(data);
        let nodesMap = getNodesMap(data);
        //获取一级节点
        rootList = findAllroot(nodeGroup, nodesMap, fields);
        //挂载一级级节点
        nodeRender(rootList, nodeGroup, []);
        tree = tree.concat(rootList);
        //删除一级节点，因为一级节点已经进入树了
        for (let prop in rootList) {
            delete nodeGroup[prop]
        }
        var usedRecord = [];
        /*第一层循环用于保证分组列表里面的每一组都在整个的节点集合中寻找它的父级，
            循环退出的条件是，分组列表里的每一项在当前的路径记录都没有对应的父节点记录*/
        do {
            usedRecord = [];
            for (let prop in nodeGroup) {
                //如果
                if (path_record.hasOwnProperty(prop)) {
                    nodeRender(nodeGroup[prop], nodeGroup, path_record[prop]);
                    var targetNode = getByPath(tree, path_record[prop]);
                    usedRecord.push(prop);
                    if (targetNode) {
                        targetNode.children = nodeGroup[prop];
                    }
                }
            }
            usedRecord.forEach(function(item) {
                delete nodeGroup[item];
            })
        } while ( usedRecord.length!=0)
        return { tree: tree, path: path_record};
    };

    if (!list || list.length == 0) {
        return {tree: [], path:{}};
    }
    var defaultFields = {
        id: "id",
        pid: "pid",
        url: "url"
    }
    var fields = Object.assign({}, defaultFields, fields);
    var path_record = {};
    return main(list)
}
// 根据 path 像 [0,3,4] 从树中寻找节点
export function getByPath(nodeTree, path) {
    if (!path) {
        return null
    }
    try {
        var tem = nodeTree;
        path.forEach(function(item, index) {
            if (index == 0) {
                if (tem.hasOwnProperty(item)) {
                    tem = tem[item];
                }
            } else {
                tem = tem.children[item];
            }
        });
        return tem;
    } catch (e) {
        console.log(e);
        return null
    }
}